package com.jstyle.beatecg.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itextpdf.kernel.events.Event;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.ble.BleManager;
import com.jstyle.beatecg.ble.BleService;
import com.jstyle.beatecg.daoManager.HrvDataDaoManager;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.model.HrvData;
import com.jstyle.beatecg.util.DateUtil;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.LanguageHelp;
import com.jstyle.beatecg.util.ResolveData;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.SendData;
import com.jstyle.beatecg.util.SharePreferenceUtils;
import com.jstyle.beatecg.view.EcgDashboardView;
import com.jstyle.beatecg.view.EcgWaveView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.jstyle.beatecg.activity.HeartHistoryShareActivity.Fileread;


public class EcgWatchActivity extends AppCompatActivity {

    private static final String TAG = "EcgWatchActivity";
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.ll_ecg_bpm)
    RelativeLayout llEcgBpm;
    /* @BindView(R.id.LineChartView_ecg)
     LineChartView LineChartViewEcg;*/
    int maxPoints = 1000;
    @BindView(R.id.tv_ecg_max)
    TextView tvEcgMax;
    @BindView(R.id.tv_ecg_avg)
    TextView tvEcgAvg;
    @BindView(R.id.tv_ecg_min)
    TextView tvEcgMin;
    @BindView(R.id.iv_ecg_back)
    ImageView ivEcgBack;
    @BindView(R.id.EcgDashboardView)
    EcgDashboardView EcgDashboardView;


    @BindView(R.id.vedio)
    Button vedio;
    @BindView(R.id.youhua)
    Button youhua;
    @BindView(R.id.stop)
    Button stop;
    @BindView(R.id.shudu)
    TextView shudu;


    private Disposable subscription;
    LinkedList<Float> queueHeart = new LinkedList<>();
    private Disposable disposable;
    int countTime;
    FileOutputStream fileOutputStream;
    private String filePath;
    private File fileOut;
    int maxHeart = 0;
    int minHeart = 0;
    int avgHeart = 0;
    int totalHeart = 0;
    int count = 0;
    private View view;
    private EcgWaveView bcgWaveView3;
    LinearLayout lLayout3;
    private MediaPlayer mediaPlayer;


    public static String Default = "Default";//默认类型
    public static String ReSTART = "ReSTART";//重新开始
    public static String RePlay = "RePlay";//数据回放
    String type = Default;
    //历史记录读取数据的标志位
    int history_indext = 0;
    int history_indextxinlv = 0;
    private static disconnNewCon disconnNewCon;

    static boolean isreadHistory = true;//是否需要读取历史记录
    AlertDialog alertDialog;

    boolean ismusic = true;//是否开启音乐
    boolean isyouhua = false;//是否优化
    boolean isdongjie = false;//是否冻结
    List<String> allhistory = new ArrayList<>();
    private List<Integer> data = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_ecg_watch);
        view = getWindow().getDecorView();
        initViewd();
        ButterKnife.bind(this);
        LanguageHelp.changeAppLanguage(this);

        allhistory.clear();
        data.clear();
        history_indextxinlv = 0;
        history_indext = 0;
        if (null != getIntent().getStringExtra("type")) {
            type = getIntent().getStringExtra("type");
        }
        //默认状态，或者重新开始才需要新建文件，开启ecg
        if (type.equals(Default) || type.equals(ReSTART)) {
            Showdevicestatus();
            createFile();
            startEcg(true);

        }
        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData data) throws Exception {
                String action = data.getAction();
                if (BleService.ACTION_GATT_DISCONNECTED.equals(action)) {
                  if(null!=disposable){  disposable.dispose();}
                    if (type.equals(Default) || type.equals(ReSTART)) {
                        Showdevicestatus();
                    }
                }  else if (BleService.ACTION_GATT_CONNECTED.equals(action)) {
                    if (type.equals(Default) || type.equals(ReSTART)) { startEcg(true);}//重新连接设备的时候需要重新计时
                }else if (BleService.ACTION_DATA_AVAILABLE.equals(action)) {
                    resolveData(data.getValue());
                } else if (RePlay.equals(action)) {//播放完成回调
                    if (!EcgWatchActivity.this.isFinishing()) {
                        if (!alertDialog.isShowing()) {
                            alertDialog.show();
                        }
                    }
                }
            }


        });

        //初始化时就创建一个MediaPlayer进行资源链接
        mediaPlayer = MediaPlayer.create(this, com.jstyle.beatecg.R.raw.xinlv);
        getViewStatus();

        if (LanguageHelp.isEnglish()) {
            shudu.setText("25mm/s  10mm/mV  0.5~40Hz  V5  " + DateUtil.getFormatTimeString(System.currentTimeMillis(), "MM/dd/yyyy HH:mm"));
        } else {
            shudu.setText("25mm/s  10mm/mV  0.5~40Hz  V5  " + DateUtil.getFormatTimeString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm"));
        }


    }


    private void ininetDialog() {
        alertDialog = new AlertDialog.Builder(EcgWatchActivity.this)
                .setTitle(R.string.tips)
                .setMessage(R.string.playback)
                .setPositiveButton(getString(R.string.playagain), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isreadHistory = true;
                        history_indextxinlv = 0;
                        history_indext = 0;
                        if (null != disconnNewCon) {
                            disconnNewCon.interrupt();
                            disconnNewCon = null;
                            disconnNewCon = new disconnNewCon();
                            disconnNewCon.start();
                        }

                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        EcgWatchActivity.this.finish();
                    }
                }).create();
    }

    private void getViewStatus() {
        if (null == SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_vedio)) {
            SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_vedio, "0");
        }
        if (null == SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_youhua)) {
            SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_youhua, "0");
        }
        if (null == SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_stop)) {
            SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_stop, "0");
        }
        if ("0".equals(SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_vedio))) {
            settingDrawables(vedio, this.getResources().getDrawable(R.drawable.vediook));
            vedio.setText(getResources().getString(R.string.volume));
            ismusic = true;
        } else {
            settingDrawables(vedio, this.getResources().getDrawable(R.drawable.vediono));
            vedio.setText(getResources().getString(R.string.silence));
            ismusic = false;
        }

        stop.setText(getResources().getString(R.string.suspend));
        youhua.setText(getResources().getString(R.string.filter));
    }


    HrvData AA;

    private void createFile() {
        File ecgFile = new File(ImageUtils.ecgPath);
        if (!ecgFile.exists()) {
            ecgFile.mkdirs();
        }
        String ttme = System.currentTimeMillis() + "";
        filePath = ImageUtils.ecgPath + ttme + ".ecg";
        AA = new HrvData();
        AA.setTimetwo(ttme);
        fileOut = new File(filePath);
        try {
            if (!fileOut.exists()) {
                fileOut.createNewFile();
            }
            fileOutputStream = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
        }
    }


    private void Showdevicestatus() {
        if (!BleService.isConnected()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(true); //设置正面按钮
            final AlertDialog dialog = builder.create();
            View normal2 = LayoutInflater.from(this).inflate(R.layout.dialog_constatus, null);
            normal2.findViewById(R.id.constatus_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(EcgWatchActivity.this, BindDeviceActivity.class));
                    dialog.dismiss();
                }
            });
            normal2.findViewById(R.id.constatus_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setView(normal2);
            dialog.show();

            WindowManager m = getWindowManager();
            Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
            android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
            p.height = (int) (d.getHeight() * 0.5);   //高度设置为屏幕的0.3
            p.width = (int) (d.getWidth() * 0.5);    //宽度设置为屏幕的0.5
            dialog.getWindow().setAttributes(p);     //设置生效

        }
    }


    private void startEcg(boolean enable) {
        BleManager.getInstance().offerValue(SendData.enableTest());
        BleManager.getInstance().offerValue(SendData.enableEcg(enable));
        BleManager.getInstance().offerValue(SendData.enableActivityHeart(enable));
        BleManager.getInstance().writeValue();
        if (BleManager.getInstance().isConnected()) startTimer(enable);
    }


    private void startTimer(boolean enable) {
        if (enable) {
            Observable.interval(0, 1, TimeUnit.SECONDS).take(120).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(Disposable d) {
                    disposable = d;
                }

                @Override
                public void onNext(Long value) {
                    countTime++;
                    if (countTime % 2 == 0) {
                        showPackage();
                    }
                   String time = DateUtil.getSportAxieTime(countTime);
                    //chronometer1.setText(time);
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onComplete() {
                    startEcg(false);
                    HrvData hrvData = getHrvData();
                    hrvData.setAllHistory(allhistory.toString());
                    hrvData.setData(data.toString());
                    Intent intent = new Intent(EcgWatchActivity.this, ReportActivity.class);
                    intent.putExtra("filepath", filePath);
                    intent.putExtra("type", "0");//当前默认为测量数据
                    intent.putExtra("data", hrvData);
                    startActivity(intent);
                    mediaPlayer.pause();
                    finish();
                }
            });
        } else {
            unsubscribe(disposable);
        }
    }


    private HrvData getHrvData() {
        HrvData hrvData = new HrvData();
        String VALUE = filePath.replace(ImageUtils.ecgPath, "");
        VALUE = VALUE.substring(0, VALUE.length() - 4);
        String time = DateUtil.getFormatTimeString(Long.valueOf(VALUE), "yy.MM.dd HH:mm:ss");
   /*     String time=DateUtil.getFormatTimeString(new Date().getTime());
        Log.e("sdsada",time);*/
        Log.e("sdsada", time);
        hrvData.setTime(time);
        hrvData.setTimetwo(AA.getTimetwo());
        hrvData.setAvgHeart(avgHeart);
        hrvData.setMaxHeart(maxHeart);
        hrvData.setMinHeart(minHeart);
        return hrvData;
    }

    private void showPackage() {
    }


    private void initViewd() {
        view.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onGlobalLayout() {
                        lLayout3 = (LinearLayout) view.findViewById(R.id.graph3_father);
                        lLayout3.removeAllViews();
                        int width = lLayout3.getWidth();
                        int height = lLayout3.getHeight();
                        bcgWaveView3 = new EcgWaveView(EcgWatchActivity.this, width, height);
                        bcgWaveView3.setN_frequency(9);//一秒几个点
                        bcgWaveView3.setSampleRe(300);//多少个点
                        bcgWaveView3.setSampleV(3);//0-10
                        bcgWaveView3.init();
                        lLayout3.addView(bcgWaveView3);
                        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        if (type.equals(RePlay)) {
                            ininetDialog();
                            //解析保存的历史记录
                            history_indext = 0;
                            history_indextxinlv = 0;
                            isreadHistory = true;
                            youhua.setEnabled(false);
                            String dateS = getIntent().getStringExtra("filepath").replace(ImageUtils.ecgPath, "");
                            final String date = dateS.substring(0, dateS.length() - 4).trim();
                            String time = DateUtil.getFormatTimeString(Long.valueOf(date.trim()), "yy.MM.dd HH:mm:ss");
                            HrvData hrvData = HrvDataDaoManager.HrvData(time);
                            ALLhistory(hrvData, 0);//解析历史数据
                            ALLhistory(hrvData, 1);
                            tvEcgAvg.setText(hrvData.getAvgHeart() + "");
                            tvEcgMax.setText(hrvData.getMaxHeart() + "");
                            tvEcgMin.setText(hrvData.getMinHeart() + "");
                            if (null != disconnNewCon) {
                                disconnNewCon.interrupt();
                                disconnNewCon = null;
                            }
                            disconnNewCon = new disconnNewCon();
                            disconnNewCon.start();
                        }
                    }
                });
    }


    int lastHr = 0;
    int lastPackage;

    private void resolveData(byte[] value) {
        if (value[0] == SendData.CMD_ECG) {
            if (value.length == 16) return;
            byte[] datas = new byte[9];
            for (int i = 0; i < 9; i++) {
                datas[i] = ResolveData.getByteArray(value[i * 2 + 1], value[i * 2 + 2]);
                final float data = ResolveData.getValue(value[i * 2 + 1], 1) + ResolveData.getValue(value[i * 2 + 2], 0);
                if (queueHeart.size() >= maxPoints) queueHeart.poll();
                Log.e("EcgWatchActivity", data + "************");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null != bcgWaveView3) {
                            if (!isdongjie) {
                                if (!isyouhua) {
                                    if (type.equals(Default) || type.equals(ReSTART)) {
                                        allhistory.add(data - 1650 + "");
                                    }
                                    bcgWaveView3.drawWave(data - 1650);
                                } else {
                                    bcgWaveView3.drawWave(getSleepQData(data));
                                }
                            }
                        }
                    }
                });
            }
            try {
                if (null != fileOutputStream) {
                    fileOutputStream.write(datas, 0, datas.length);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            // if(queueHeart.size()%18==0)
        } else if (value[0] == SendData.CMD_ENABLE_ACTIVITY_HEART) {
            float heartRate = ResolveData.getValue(value[1], 0);
            Log.i(TAG, "resolveData: " + heartRate);
            if (heartRate > 200 || heartRate < 40) return;
            lastHr = (int) heartRate;
            if (maxHeart == 0) maxHeart = lastHr;
            if (minHeart == 0) minHeart = lastHr;
            totalHeart += lastHr;
            if (lastHr > maxHeart) maxHeart = lastHr;
            if (lastHr < minHeart) minHeart = lastHr;
            count++;
            avgHeart = totalHeart / count;
            tvEcgAvg.setText(avgHeart + "");
            tvEcgMax.setText(maxHeart + "");
            tvEcgMin.setText(minHeart + "");
            EcgDashboardView.updateData(lastHr);
            data.add(lastHr);
            medio(ismusic, lastHr);
            //textEcgVal1.setText(lastHr + "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        startTimer(false);
        countTime=0;
        if (type.equals(Default) || type.equals(ReSTART)) {
            if (fileOut.exists() && fileOut.length() == 0) {
                fileOut.delete();
            }
            startEcg(false);
            unsubscribe(subscription);
        } else {
            isreadHistory = false;
            history_indextxinlv = 0;
            history_indext = 0;
            disconnNewCon.interrupt();
            disconnNewCon = null;
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            // mediaPlayer=null;
        }
    }

    private void unsubscribe(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @OnClick({R.id.iv_ecg_back, R.id.vedio, R.id.stop, R.id.youhua})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_ecg_back:
                finish();
                break;
            case R.id.vedio:
                if (ismusic) {
                    ismusic = false;
                    settingDrawables(vedio, this.getResources().getDrawable(R.drawable.vediono));
                    vedio.setText(getResources().getString(R.string.silence));
                    SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_vedio, "1");
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                    }
                } else {
                    ismusic = true;
                    settingDrawables(vedio, this.getResources().getDrawable(R.drawable.vediook));
                    vedio.setText(getResources().getString(R.string.volume));
                    SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_vedio, "0");
                }
                break;
            case R.id.stop:
                if (type.equals(Default) || type.equals(ReSTART)) {
                    if (BleManager.getInstance().isConnected()) {
                        if (!isdongjie) {
                            isdongjie = true;
                            ismusic = false;
                            settingDrawables(stop, this.getResources().getDrawable(R.drawable.stopok));
                            stop.setText(getResources().getString(R.string.continues));
                            medio(ismusic, lastHr);
                        } else {
                            isdongjie = false;
                            ismusic = true;
                            settingDrawables(stop, this.getResources().getDrawable(R.drawable.stopno));
                            stop.setText(getResources().getString(R.string.suspend));
                            medio(ismusic, lastHr);
                        }
                    } else {
                        Toast.makeText(this, getResources().getString(R.string.Bluetooth_Disconnected), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //历史回放的情况下
                    if (isreadHistory) {
                        isreadHistory = false;
                        settingDrawables(stop, this.getResources().getDrawable(R.drawable.stopok));
                        stop.setText(getResources().getString(R.string.continues));
                        medio(ismusic, data.get(history_indextxinlv));
                        Thread.currentThread().interrupt();// 再调用interrupt方法
                        disconnNewCon.interrupt();
                    } else {
                        isreadHistory = true;
                        settingDrawables(stop, this.getResources().getDrawable(R.drawable.stopno));
                        stop.setText(getResources().getString(R.string.suspend));
                        medio(ismusic, data.get(history_indextxinlv));
                        if (null != disconnNewCon) {
                            disconnNewCon.interrupt();
                            disconnNewCon = null;
                            disconnNewCon = new disconnNewCon();
                            disconnNewCon.start();
                        }

                    }

                }
                break;

            case R.id.youhua:
                if (BleManager.getInstance().isConnected()) {
                    if (!isyouhua) {
                        isyouhua = true;
                        settingDrawables(youhua, this.getResources().getDrawable(R.drawable.youhuaok));
                        youhua.setText(getResources().getString(R.string.filter));
                        youhua.setTextColor(getResources().getColor(R.color.m000000));
                    } else {
                        isyouhua = false;
                        settingDrawables(youhua, this.getResources().getDrawable(R.drawable.youhuano));
                        youhua.setText(getResources().getString(R.string.filter));
                        youhua.setTextColor(getResources().getColor(R.color.m999999));
                    }
                } else {
                    Toast.makeText(this, getResources().getString(R.string.Bluetooth_Disconnected), Toast.LENGTH_SHORT).show();
                }
                break;

        }


    }


    static Double Bdatas[] = {0.045140667948225, 0.0, -0.090281335896450, 0.0, 0.045140667948225};
    static Double Adatas[] = {1.0000, -3.310257394625900, 4.118311073459422, -2.304211033269888, 0.496164660508347};
    static double[] tmp_x = new double[9];
    static double[] tmp_y = new double[9];

    public static float getSleepQData(float dat) {
        for (int i = 4; i > 0; i--) {
            tmp_x[i] = tmp_x[i - 1];
            tmp_y[i] = tmp_y[i - 1];
        }
        tmp_x[0] = (dat + tmp_x[1] + tmp_x[2] + tmp_x[3] + tmp_x[4]) / 5;
        tmp_y[0] = Bdatas[0] * tmp_x[0] +
                Bdatas[1] * tmp_x[1] +
                Bdatas[2] * tmp_x[2] +
                Bdatas[3] * tmp_x[3] +
                Bdatas[4] * tmp_x[4] -
                Adatas[1] * tmp_y[1] -
                Adatas[2] * tmp_y[2] -
                Adatas[3] * tmp_y[3] -
                Adatas[4] * tmp_y[4];
        float value;

        //Log.e("value", - tmp_y[0]*5+3+"");
        value = ((float) (-tmp_y[0] * 5 + 3) * 1.75f);
        if (value > 0) {
            value = value + 50f;
            if (value > 6000) {
                value = 5500;
            }
        } else {
            value = (value - 50f) / 2;
            if (value < -6000) {
                value = -5500;
            }
        }
        Log.e("value", "value" + value);
        return value;
    }


    /**
     * 声音开关
     *
     * @param status
     */
    private void medio(boolean status, int type) {
        //type>100其他音乐
        if (type >= 100) {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = MediaPlayer.create(this, com.jstyle.beatecg.R.raw.xinlvji);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        } else {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = MediaPlayer.create(this, com.jstyle.beatecg.R.raw.xinlv);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
        if (!status) {
            mediaPlayer.pause();
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!mediaPlayer.isPlaying()) { // 开始播放
                            mediaPlayer.start();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, (60 / type) * 1000);
        }
    }

    //设置图片
    private void settingDrawables(Button button, Drawable drawable) {
        button.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable, null, null);
    }


    /**
     * 解析历史数据
     *
     * @param hrvData
     */
    private void ALLhistory(HrvData hrvData, int type) {
        String[] VALUE;
        if (0 == type) {
            VALUE = ((hrvData.getAllHistory().replace("[", "")).replace("]", "")).split(",");
        } else {
            VALUE = ((hrvData.getData().replace("[", "")).replace("]", "")).split(",");
        }
        for (int i = 0; i < VALUE.length; i++) {
            if (0 == type) {
                allhistory.add(VALUE[i].trim());
            } else {
                data.add(Integer.valueOf(VALUE[i].trim()));
            }

        }
    }

    /**
     * 历史数据返回方法
     */
    private Float hosValue(int index) {
        if (index < allhistory.size()) {
            return Float.valueOf(allhistory.get(index));
        } else {
            return -1f;
        }
    }

    private long lastClickTime = 0L;
    // 两次点击间隔不能少于1000ms
    private static final int FAST_CLICK_DELAY_TIME = 1500;

    class disconnNewCon extends Thread {
        @Override
        public void run() {
            try {
                while (isreadHistory) {
                    //这儿是耗时操作，完成之后更新UI；
                    sleep(3);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (history_indext == allhistory.size() - 1) {
                                if (null != disconnNewCon) {
                                    isreadHistory = false;
                                    Thread.currentThread().interrupt();// 再调用interrupt方法
                                    disconnNewCon.interrupt();
                                    if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                                        return;
                                    }
                                    lastClickTime = System.currentTimeMillis();
                                    Log.e("fdsfds", "dfsdfsfsdfdsds");
                                    BleData bleData = new BleData();
                                    bleData.setAction(RePlay);
                                    RxBus.getInstance().post(bleData);

                                }
                            } else {
                                if (history_indext < allhistory.size() - 1) {
                                    bcgWaveView3.drawWave(hosValue(history_indext));
                                    history_indext++;
                                }

                                if (history_indextxinlv < data.size() - 1) {
                                    if (history_indext % (allhistory.size() / data.size()) == 0) {
                                        EcgDashboardView.updateData(data.get(history_indextxinlv));
                                        medio(ismusic, data.get(history_indextxinlv));
                                        history_indextxinlv++;
                                    }
                                }
                            }


                        }
                    });

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
